package com.jkc.xh.adapters.viewholder;

import android.content.Context;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jkc.xh.R;
import com.jkc.xh.manager.TraderManager;
import com.jkc.xh.manager.UserManager;
import com.jkc.xh.models.StockInfoModel;
import com.jkc.xh.network.RestCallBack;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.network.models.SystemHintResponse;
import com.jkc.xh.utils.Tool;
import com.jkc.xh.views.widget.ToastUtil;

import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

import retrofit.Call;

/**
 * Created by wangjie28 on 2015/11/13.
 */
@EViewGroup(R.layout.layout_head_auto_sell)
public class HeadViewAutoSell extends RelativeLayout {
    @ViewById
    TextView stock_code;
    @ViewById
    TextView stock_name;
    @ViewById
    TextView buy_price1;
    @ViewById
    TextView buy_price2;
    @ViewById
    TextView buy_price3;
    @ViewById
    TextView buy_price4;
    @ViewById
    TextView buy_price5;
    @ViewById
    TextView sale_price1;
    @ViewById
    TextView sale_price2;
    @ViewById
    TextView sale_price3;
    @ViewById
    TextView sale_price4;
    @ViewById
    TextView sale_price5;
    @ViewById
    TextView buy_amount1;
    @ViewById
    TextView buy_amount2;
    @ViewById
    TextView buy_amount3;
    @ViewById
    TextView buy_amount4;
    @ViewById
    TextView buy_amount5;
    @ViewById
    TextView sale_amount1;
    @ViewById
    TextView sale_amount2;
    @ViewById
    TextView sale_amount3;
    @ViewById
    TextView sale_amount4;
    @ViewById
    TextView sale_amount5;
    @ViewById
    TextView close_price;
    @ViewById
    TextView open_price;
    @ViewById
    TextView high_price;
    @ViewById
    TextView low_price;
    @ViewById
    TextView down_price;
    @ViewById
    TextView up_price;
    @ViewById
    TextView hintInfo;
    @ViewById
    TextView last_price;
    @ViewById
    EditText priceEnter;
    @ViewById
    EditText priceDownEnter;
    @ViewById
    EditText maxcountEnter;
    @ViewById
    EditText inputStockCode;

    private double minUPrice;
    private double currentPrice;
    private double downPrice = 0;
    private String stockDownPrice;
    private String stockUpPrice;
    private long currentBuyCount;

    private long maxBuyCount = 0;
    private String currentCode;
    /*是否加载成功*/
    private boolean isLoadFinish = false;

    private HeadCallBack headCallBack;
    private String hid;

    public HeadViewAutoSell(Context context) {
        this(context, null);
    }

    public HeadViewAutoSell(Context context, AttributeSet attrs) {
        super(context, attrs);
        addJob(UserManager.getCpmfHintConfig(new RestCallBack<SystemHintResponse>() {
            @Override
            public void success(SystemHintResponse obj) {
                hintInfo.setText(Html.fromHtml(obj.autobuy_time));
            }

            @Override
            public void failure(RestError error) {

            }
        }));
    }


    protected ArrayList<Call> mCallArray = new ArrayList<>();

    protected void addJob(Call call) {
        mCallArray.add(call);
    }

    @Background
    public void clearAllJob() {
        for (Call call : mCallArray) {
            if (call != null) {
                call.cancel();
            }
        }
    }

    @AfterViews
    void bindView() {
        maxcountEnter.setText("");
        currentBuyCount = 0;

    }

    /**
     * 离开界面时 隐藏键盘
     */
    public void closeSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(priceEnter.getWindowToken(), 0);
    }

    /**
     * 刷新
     */
    public void reloadStockInfo() {
        if (!TextUtils.isEmpty(currentCode)) {
            loadStockInfo(currentCode, hid, maxBuyCount + "");
        }
    }

    /**
     * 加载个股信息
     *
     * @param code
     */
    public void loadStockInfo(String code, String hid, String enable_amount) {
        currentCode = code;
        maxBuyCount = Long.valueOf(enable_amount);
        this.hid = hid;
        inputStockCode.setText(currentCode + "");
        bindView();
        showProgress();
        isLoadFinish = false;
        addJob(TraderManager.queryStockInfoRequest(code, new RestCallBack<StockInfoModel>() {
            @Override
            public void success(StockInfoModel model) {
                stock_code.setText(model.stock_code);
                stock_name.setText(model.stock_name);
                buy_price1.setText(model.buy_price1);
                buy_price2.setText(model.buy_price2);
                buy_price3.setText(model.buy_price3);
                buy_price4.setText(model.buy_price4);
                buy_price5.setText(model.buy_price5);
                sale_price1.setText(model.sale_price1);
                sale_price2.setText(model.sale_price2);
                sale_price3.setText(model.sale_price3);
                sale_price4.setText(model.sale_price4);
                sale_price5.setText(model.sale_price5);
                buy_amount1.setText(model.buy_amount1);
                buy_amount2.setText(model.buy_amount2);
                buy_amount3.setText(model.buy_amount3);
                buy_amount4.setText(model.buy_amount4);
                buy_amount5.setText(model.buy_amount5);
                sale_amount1.setText(model.sale_amount1);
                sale_amount2.setText(model.sale_amount2);
                sale_amount3.setText(model.sale_amount3);
                sale_amount4.setText(model.sale_amount4);
                sale_amount5.setText(model.sale_amount5);

                /*股票价格信息*/
                close_price.setText(Tool.formatPrice(model.close_price));
                open_price.setText(Tool.formatPrice(model.open_price));
                high_price.setText(Tool.formatPrice(model.high_price));
                low_price.setText(Tool.formatPrice(model.low_price));
                down_price.setText(Tool.formatPrice(model.down_price));
                up_price.setText(Tool.formatPrice(model.up_price));
                priceEnter.setText("");
                priceDownEnter.setText("");

                minUPrice = model.last_price;
                stockUpPrice = model.up_price;
                stockDownPrice = model.down_price;
                currentPrice = model.last_price;
                downPrice = model.last_price;
                last_price.setText(Tool.formatPrice(model.last_price));

                isLoadFinish = true;

                maxcountEnter.setText(enable_amount);
                currentBuyCount = maxBuyCount;
                closeProgress();
            }

            @Override
            public void failure(RestError error) {
                closeProgress();
            }
        }));

    }

    void closeProgress() {
        if (headCallBack != null) {
            headCallBack.loadEnd();
        }
    }

    void showProgress() {
        if (headCallBack != null) {
            headCallBack.loadStart();
        }
    }

    @AfterTextChange(R.id.priceEnter)
    void priceChange(TextView tv, Editable text) {
        String price = text.toString();
        if (!TextUtils.isEmpty(price)) {
            try {
                if (price.contains(".")) {
                    int index = price.indexOf(".");
                    if (index + 3 < price.length()) {
                        price = price.substring(0, index + 3);
                        priceEnter.setText(price);
                        priceEnter.setSelection(price.length());
                    } else {
                        currentPrice = Double.valueOf(price);
                    }
                } else {
                    currentPrice = Double.valueOf(price);
                }

            } catch (Exception e) {

            }
        }
    }


    @Click(R.id.priceSub)
    void clickPriceSub() {
        if (!checkLoadFinish()) {
            return;
        }
        currentPrice = loadEnterUpPrice();
        if (currentPrice - 0.01 <= minUPrice + 0.009) {
            ToastUtil.showToastShort("上涨触发价格不能低于或等于当前价");
            currentPrice = minUPrice + 0.01;
            priceEnter.setText(Tool.formatPrice(currentPrice));
            return;
        }
        currentPrice = currentPrice - 0.01;
        priceEnter.setText(Tool.formatPrice(currentPrice));
    }


    @Click(R.id.priceAdd)
    void clickPriceAdd() {
        if (!checkLoadFinish()) {
            return;
        }
        currentPrice = loadEnterUpPrice();
        if (currentPrice + 0.01 <= minUPrice) {
            ToastUtil.showToastShort("上涨触发价格不能低于或等于当前价");
            currentPrice = minUPrice;
        }
        currentPrice = currentPrice + 0.01;
        priceEnter.setText(Tool.formatPrice(currentPrice));
    }

    @Click(R.id.priceDownSub)
    void clickPriceDownSub() {
        if (!checkLoadFinish()) {
            return;
        }
        downPrice = loadEnterDownPrice();
        Double priceLow = Double.valueOf(Tool.formatPrice(stockDownPrice));
        if (downPrice - 0.01 <= priceLow) {
            ToastUtil.showToastShort("委托价格必须大于跌停价");
            return;
        }
        if (downPrice - 0.01 >= minUPrice) {
            ToastUtil.showToastShort("下跌触发价格不能大于或等于当前价");
            downPrice = minUPrice;
        }
        downPrice = downPrice - 0.01;
        priceDownEnter.setText(Tool.formatPrice(downPrice));
    }

    @Click(R.id.priceDownAdd)
    void clickPriceDownAdd() {
        if (!checkLoadFinish()) {
            return;
        }
        downPrice = loadEnterDownPrice();
        if (downPrice + 0.01 >= minUPrice - 0.009) {
            ToastUtil.showToastShort("下跌触发价格不能大于或等于当前价");
            downPrice = minUPrice - 0.01;
            priceDownEnter.setText(Tool.formatPrice(downPrice));
            return;
        }
        downPrice = downPrice + 0.01;
        priceDownEnter.setText(Tool.formatPrice(downPrice));
    }

    private double loadEnterDownPrice() {
        String enterPrice = priceDownEnter.getText().toString();
        double price = downPrice;
        try {
            Double currentPrice = Double.valueOf(enterPrice);
            price = currentPrice;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return price;
    }

    private double loadEnterUpPrice() {
        String enterPrice = priceEnter.getText().toString();
        double price = currentPrice;
        try {
            Double currentPrice = Double.valueOf(enterPrice);
            price = currentPrice;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return price;
    }


    @Click(R.id.countAdd)
    void clickCountAdd() {
        if (!checkLoadFinish()) {
            return;
        }
        loadCurrentCount();
        if (currentBuyCount + 100 > maxBuyCount) {
            ToastUtil.showToastShort("超过最大可卖数量");
            currentBuyCount = maxBuyCount;
            return;
        }
        currentBuyCount += 100;
        maxcountEnter.setText(currentBuyCount + "");
    }

    private long loadCurrentCount() {
        String input = maxcountEnter.getText().toString();
        if (TextUtils.isEmpty(input)) {
            currentBuyCount = 0;
        } else {
            currentBuyCount = Long.valueOf(input);
        }
        return currentBuyCount;
    }

    @Click(R.id.countSub)
    void clickCountSub() {
        if (!checkLoadFinish()) {
            return;
        }
        loadCurrentCount();
        if (currentBuyCount - 100 < 100) {
            ToastUtil.showToastShort("至少100股");
            return;
        }
        currentBuyCount -= 100;
        maxcountEnter.setText(currentBuyCount + "");
    }

    @Click(R.id.buyStock)
    void clickBuyStock() {
        if (!checkLoadFinish()) {
            return;
        }
        /*检查价格是够合格*/
        String currentPrice = priceEnter.getText().toString();
        if (!isIlegalPrice(currentPrice)) {
            return;
        }
        String downPrice = priceDownEnter.getText().toString();
        if (!isIlegalDownPrice(downPrice)) {
            return;
        }
        /*检查买入数量是够合格*/
        long input = loadCurrentCount();
        if (input <= 0) {
            ToastUtil.showToastShort("至少需要卖出100股");
            return;
        }
        if (input > maxBuyCount) {
            ToastUtil.showToastShort("自动卖出委托失败,当前最大可卖" + maxBuyCount);
            return;
        }
        showProgress();
        addJob(TraderManager.autoSell(currentCode, currentPrice + "", downPrice + "", input, hid, new RestCallBack<Object>() {
            @Override
            public void success(Object o) {
                closeProgress();
                ToastUtil.showToastShort(R.string.order_success);
            }

            @Override
            public void failure(RestError error) {
                closeProgress();
                ToastUtil.showToastShort(error.msg);
            }

        }));
    }

    /**
     * 输入价格适合合法
     *
     * @return
     */
    public boolean isIlegalPrice(String enterPrice) {
        boolean isEnough = false;
        try {
            Double currentPrice = Double.valueOf(enterPrice);
            if (currentPrice <= minUPrice) {
                ToastUtil.showToastShort("上涨触发价格不能低于或等于当前价");
            } else {
                isEnough = true;
            }

        } catch (Exception e) {

        }
        return isEnough;
    }

    /**
     * 输入价格适合合法
     *
     * @return
     */
    public boolean isIlegalDownPrice(String enterPrice) {
        boolean isEnough = false;
        try {
            Double currentPrice = Double.valueOf(enterPrice);
            if (currentPrice >= minUPrice) {
                ToastUtil.showToastShort("下跌触发价格不能大于或等于当前价");
            } else {
                isEnough = true;
            }
        } catch (Exception e) {

        }
        return isEnough;
    }


    /**
     * 检验是否加载股票信息完毕.
     * 并做出提示
     *
     * @return
     */
    private boolean checkLoadFinish() {
        if (!isLoadFinish) {
            ToastUtil.showToastShort("股票信息还没加载完成");
        }
        return isLoadFinish;
    }

    public void setHeadCallBack(HeadCallBack headCallBack) {
        this.headCallBack = headCallBack;
    }

    public interface HeadCallBack {
        void loadStart();

        void loadEnd();
    }
}
